from django.utils import timezone
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
from .models import Blog

def user_login(request):
    if request.method == "POST":
        username = request.POST["username"]
        password = request.POST["password"]
        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
            return redirect("blogs:index")
        else:
            return render(request, "Blog/login.html", {"error": "Invalid username or password."})
    else:
        return render(request, "Blog/login.html")
    
def index(request):
    return render(request, "Blog/index.html")

def blogs(request):
    latest_blogs = Blog.objects.order_by("-pub_date")[:5]
    context = {
        "latest_blogs": latest_blogs,
    }
    return render(request, "Blog/blogs.html", context)

def content(request, blog_id):
    blog = get_object_or_404(Blog, pk=blog_id)
    return render(request, "Blog/content.html", {"blog": blog.content})

@login_required
def new_post(request):
    return render(request, "Blog/new_post.html")

def save_post(request):
    blog = Blog()
    blog.pub_date = timezone.now()
    blog.content = request.POST["content"]
    blog.title = request.POST["title"]
    blog.save()
    return render(request, "Blog/content.html", {"blog": blog.content})